#include "Stack.h"

#define _CRT_SECURE_NO_WARNINGS

void StackInit(Stack* ps)
{
	DataType* space = (DataType*)malloc(sizeof(DataType));
	if (space)
	{
		ps->a = space;
		ps->capacity = 1;
		ps->top = 0;
	}
	else
	{
		perror("StackInit:malloc");
		exit(-1);
	}
}

void StackPush(Stack* ps, DataType x)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		DataType* space = (DataType*)realloc(ps->a, sizeof(DataType) * 2 * ps->capacity);
		if (space)
		{
			ps->a = space;
			ps->capacity *= 2;
		}
		else
		{
			perror("realloc:");
			exit(-1);
		}
	}
	ps->a[ps->top++] = x;
}

void StackPop(Stack* ps)
{
	assert(ps->top > 0);
	ps->top--;
}

void StackDestory(Stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top;
}

bool StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->top == 0;
}

DataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->a[ps->top - 1];
}
